import { createRouter, createWebHistory } from 'vue-router'
import HrmsIndex from "@/views/HrmsIndex.vue";
import HrmsRegister from "@/views/HrmsRegister.vue";
import CommonUserIndex from "@/views/CommonUserIndex.vue";
import HrUserIndex from "@/views/HrUserIndex.vue";
import AdminUserIndex from "@/views/AdminUserIndex.vue";


const routes = [
  {
    path: '/',
    name: 'HrmsIndex',
    component: HrmsIndex
  },
  {
    path: '/HrmsRegister',
    name: 'HrmsRegister',
    component: HrmsRegister
  },
  {
    path: '/CommonUserIndex',
    name: 'CommonUserIndex',
    component: CommonUserIndex,
    meta: { requiresAuth: true, role: 2 },
  },
  {
    path: '/HrUserIndex',
    name: 'HrUserIndex',
    component: HrUserIndex,
    meta: { requiresAuth: true, role: 3 },
  },
  {
    path: '/AdminUserIndex',
    name: 'AdminUserIndex',
    component: AdminUserIndex,
    meta: { requiresAuth: true, role: 1 },
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token');
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));

  // 如果需要认证并且没有 token，跳转到登录页面
  if (to.meta.requiresAuth && !token) {
    return next('/');
  }

  // 如果有 token，但权限不足，跳转到权限不足页面或登录页
  if (to.meta.requiresAuth && userInfo && userInfo.roleId !== to.meta.role) {
    return next('/'); // 可以跳转到其他页面显示权限不足
  }

  next(); // 如果通过认证，继续访问页面
});
export default router
